//
//  HEOrgDetailsViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/26.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEOrgDetailsViewController.h"
#import "HEOrgHeadCell.h"
#import "HEOrgTextCell.h"
#import <RZColorful/RZColorful.h>
#import "HEOrgPhotoCell.h"
#import "HEOrgConectCell.h"
#import "HEOrgBaseCell.h"
#import "KNActionSheet.h"

@interface HEOrgDetailsViewController ()<UITableViewDelegate, UITableViewDataSource, HEOrgHeadCellDataSourceDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) HEOldPelOrgModel *details;

@end

@implementation HEOrgDetailsViewController

 
- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"机构详请";
 
    [self.view addSubview:self.tableView];
    
    [self tabbarView];
    [self loadData];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight - 49 - ZXSafeAreaBottom) style:UITableViewStyleGrouped];
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    return _tableView;
}

- (void)initCell {
    
    _sections = @[].mutableCopy;
    _dataSource = @[@"",@"", @"",
                    [self dealhtml:IsNotNull(_details.jgjs)],
                    [self dealhtml:IsNotNull(_details.hjssjs)],
                     [self dealhtml:IsNotNull(_details.rzxz)],
                      [self dealhtml:IsNotNull(_details.sfbz)],
                    @""].mutableCopy;
    
    self.formModel.dataSource = _dataSource;

    NSMutableArray *classArr = [NSMutableArray array];
    
    //
    GDFiterCellModel *headModel = [GDFiterCellModel new];
    headModel.cellKlass = HEOrgHeadCell.class;
    
    GDFiterCellModel *baseModel = [GDFiterCellModel new];
    baseModel.cellKlass = HEOrgBaseCell.class;
    baseModel.leftTitle = @"基本信息";
    
    GDFiterCellModel *lsModel = [GDFiterCellModel new];
    lsModel.cellKlass = HEOrgConectCell.class;
    lsModel.leftTitle = @"联系我们";
    
    GDFiterCellModel *briefModel = [GDFiterCellModel new];
    briefModel.cellKlass = HEOrgTextCell.class;
    briefModel.leftTitle = @"机构介绍";
    
    GDFiterCellModel *hjModel = [GDFiterCellModel new];
    hjModel.cellKlass = HEOrgTextCell.class;
    hjModel.leftTitle = @"环境介绍";
    
    GDFiterCellModel *rzModel = [GDFiterCellModel new];
    rzModel.cellKlass = HEOrgTextCell.class;
    rzModel.leftTitle = @"入驻须知";
    
    GDFiterCellModel *sfModel = [GDFiterCellModel new];
    sfModel.cellKlass = HEOrgTextCell.class;
    sfModel.leftTitle = @"收费标准";
    
    GDFiterCellModel *photoModel = [GDFiterCellModel new];
    photoModel.cellKlass = HEOrgPhotoCell.class;
    photoModel.leftTitle = @"图片展示";
    
    
 
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[headModel, baseModel, lsModel, briefModel, hjModel, rzModel, sfModel, photoModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
 
    for (GDFiterCellModel *model in classArr) {
        
        NSMutableArray *sec = @[].mutableCopy;
        [sec addObject: model];
        [_sections addObject:sec];
    }
      
    [self.tableView reloadData];
}

- (NSMutableAttributedString *)dealhtml:(NSString *)str {
    NSMutableAttributedString *attr = [NSAttributedString htmlString: str].mutableCopy;

    // 图片的尺寸，在转换保存的时候，是保存的图片本身的size（px），在转换为富文本的时候，并没有转为pt，所以会有可能变大并别裁剪，这里做一个尺寸适配
    NSArray <RZAttributedStringInfo *> *array = [attr rz_attributedStringByAttributeName:NSAttachmentAttributeName];
    [array enumerateObjectsUsingBlock:^(RZAttributedStringInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSTextAttachment *att = obj.value;
        UIImage *image = att.image;
        if (image == nil) {
            image = [UIImage imageWithData:att.fileWrapper.regularFileContents];
        }
        CGFloat width = MIN(image.size.width, KScreenWidth - 20);
        CGFloat height = MIN(image.size.height, image.size.height * width / image.size.width);
        CGRect bounds = att.bounds;
        bounds.size = CGSizeMake(width, height);
        NSAttributedString *temp = [NSAttributedString rz_colorfulConfer:^(RZColorfulConferrer *confer) {
            confer.image(image).bounds(bounds);
        }];
        [attr replaceCharactersInRange:obj.range withAttributedString:temp];
    }];
    [attr addAttributes:@{NSFontAttributeName: DYFont(16)} range:NSMakeRange(0, attr.length)];

    
//        NSMutableAttributedString *htmlString = [[NSMutableAttributedString alloc] initWithData:[self.detailMobileHtml dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];;
    return attr;
}


- (void)loadData {
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KOrgDetails parameters:@{@"sanatoriumId" : [NSNumber numberWithInteger:_orgId]} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.details = [HEOldPelOrgModel mj_objectWithKeyValues:response.data];
        
        [self.tableView reloadData];
        
        [self initCell];

    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)tabbarView {
    
    UIView *view = [UIView new];
    [self.view addSubview:view];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-ZXSafeAreaBottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_offset(49);
    }];
    
    UIButton *consulBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    consulBtn.titleLabel.font = DYBlodFont(15);
    [consulBtn setBackgroundColor:CNavBgColor];
    [consulBtn setTitle:@"拨打电话" forState:UIControlStateNormal];
    [view addSubview:consulBtn];
    [consulBtn addTarget:self action:@selector(callPhoneClick) forControlEvents:UIControlEventTouchUpInside];
    
    [consulBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view);
        make.bottom.equalTo(view);
        make.right.equalTo(view);
        make.width.mas_offset(130);
    }];
}

- (void)callPhoneClick {
    
    NSMutableArray *allPhones = @[].mutableCopy;
    if (![DYTools isBlankString:_details.gddh]) {
        NSArray *phones = [_details.gddh componentsSeparatedByString:@"/"];
        [allPhones addObjectsFromArray:phones];
    }
    
    if (![DYTools isBlankString:_details.yddh] && ![@"-" isEqualToString:_details.yddh]) {
        NSArray *phones = [_details.yddh componentsSeparatedByString:@"/"];
        [allPhones addObjectsFromArray:phones];
    }
    
    KNActionSheet *sheet = [[KNActionSheet alloc] initWithTitle:nil cancelTitle:@"取消" titleArray:allPhones  actionSheetBlock:^(NSInteger buttonIndex) {
        if (buttonIndex >= 0) {
            [DYTools callPhone:allPhones[buttonIndex]];
        }
    }];
    [sheet show];
}
 

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];

    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    fiterModel.fiterCellModelBlock(cell, fiterModel, self.formModel, indexPath);
    [cell configCellWithModel:_details];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
 
  return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
      fiterModel.fiterCellModelBlock(cell, fiterModel, self.formModel, indexPath);
      [cell configCellWithModel:self.details];
   }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
}

#pragma mark - HEOrgHeadCellDataSourceDelegate
- (id)cellDataWithIndexPath:(NSIndexPath *)indexPath {
    return _details;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
 
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
    return v;
}
 
 
@end
